package com.dzjcloud.dzj.common.core.utils;

import cn.hutool.json.JSONUtil;
import com.dzjcloud.dzj.common.core.enums.ResultEnum;
import lombok.experimental.UtilityClass;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.Objects;

/**
 * <h3>bangbang</h3>
 * <p>返回工具类</p>
 *
 * @author : DongZeJian
 * @date : 2020-12-31 16:13
 **/
@UtilityClass
public class HttpRUtils {

	/**
	 * 返回成功
	 *
	 * @param object: 返回对象
	 * @return HttpResult
	 */
	public static R success(Object object) {
		R httpR = new R();
		httpR.setCode(ResultEnum.SUCCESS_CODE.getCode());
		httpR.setMsg(ResultEnum.SUCCESS_CODE.getMessage());
		httpR.setData(object);
		return httpR;
	}

	/**
	 * 返回成功
	 *
	 * @param code   : 返回成功状态码
	 * @param object : 返回对象
	 * @return
	 */
	public R success(Integer code, Object object) {
		R httpR = new R();
		httpR.setCode(code);
		httpR.setMsg(ResultEnum.SUCCESS_CODE.getMessage());
		httpR.setData(object);
		return httpR;
	}

	/**
	 * 返回成功
	 *
	 * @param code: 返回状态吗
	 * @param msg
	 * @return
	 */
	public R success(Integer code, String msg) {
		R httpR = new R();
		httpR.setCode(code);
		httpR.setMsg(msg);
		httpR.setData(null);
		return httpR;
	}

	/**
	 * 返回成功
	 *
	 * @param code:  返回状态吗
	 * @param msg
	 * @param object
	 * @return
	 */
	public R success(Integer code, String msg, Object object) {
		R httpR = new R();
		httpR.setCode(code);
		httpR.setMsg(msg);
		httpR.setData(object);
		return httpR;
	}

	/**
	 * 返回成功
	 *
	 * @return HttpResult
	 */
	public R success() {
		return success(null);
	}

	/**
	 * 返回错误
	 *
	 * @param code: 错误码
	 * @param msg:  错误信息
	 * @return
	 */
	public R error(Integer code, String msg) {
		R httpR = new R();
		httpR.setCode(code);
		httpR.setMsg(msg);
		return httpR;
	}

	/**
	 * 异常拦截器返回错误
	 *
	 * @param msg: 错误信息
	 * @return
	 */
	public static R error(String msg) {
		R httpR = new R();
		httpR.setCode(ResultEnum.ERROR_CODE.getCode());
		httpR.setMsg(msg);
		return httpR;
	}

	/**
	 * 封装response返回异常json格式
	 *
	 * @param response : response返回
	 * @throws IOException
	 */
	public void responseError(HttpServletResponse response, Integer code, String msg) throws IOException {
		if (Objects.isNull(response)) {
			return;
		}
		response.setStatus(HttpServletResponse.SC_FORBIDDEN);
		response.setContentType("application/json;charset=UTF-8");
		PrintWriter writer = response.getWriter();
		R httpR =HttpRUtils.error(code, msg);
		String jsonStr = JSONUtil.toJsonStr(httpR);
		writer.write(jsonStr);
		writer.flush();
		writer.close();
	}
}
